import random
from datetime import datetime

# 商品数据库 - 使用列表存储商品信息 (商品名, 价格)
products = [
    ("苹果", 5.5),
    ("香蕉", 3.2),
    ("牛奶", 8.0),
    ("鸡蛋", 12.5),
    ("面包", 6.8),
    ("矿泉水", 2.0),
    ("啤酒", 7.5),
    ("空调", 2999.0),
    ("电视", 3999.0),
    ("洗衣机", 2599.0)
]

# 10张真实有效的优惠券 (商品名, 折扣率)
coupons = [
    ("空调", 0.8),  # 8折
    ("电视", 0.85),  # 85折
    ("洗衣机", 0.9),  # 9折
    ("啤酒", 0.7),  # 7折
    ("鸡蛋", 0.75),  # 75折
    ("牛奶", 0.85),  # 85折
    ("面包", 0.8),  # 8折
    ("苹果", 0.9),  # 9折
    ("香蕉", 0.8),  # 8折
    ("矿泉水", 0.5)  # 5折
]


def get_random_coupon():
    """随机抽取一张真实有效的优惠券"""
    return random.choice(coupons)


def display_products():
    """显示商品列表"""
    print("\n商品列表:")
    for idx, (name, price) in enumerate(products, 1):
        print(f"{idx}. {name} - ￥{price:.2f}")


def display_cart(cart):
    """显示购物车内容"""
    if not cart:
        print("购物车是空的")
        return

    print("\n当前购物车:")
    for idx, (name, price, original_price) in enumerate(cart, 1):
        if price == original_price:
            print(f"{idx}. {name} - ￥{price:.2f}")
        else:
            print(f"{idx}. {name} - ￥{price:.2f} (原价:￥{original_price:.2f}, 优惠价)")


def shopping_system_v2():
    # 初始化用户账户
    money = float(input("请输入您的账户余额: "))
    original_money = money

    # 随机抽取优惠券 (保证100%有真实优惠)
    coupon_product, discount = get_random_coupon()
    print(f"\n恭喜! 您抽到了【{coupon_product} {int(discount * 10)}折】优惠券!")

    # 创建空购物车 (使用列表)
    shopping_cart = []

    # 显示商品列表
    display_products()

    while True:
        print(f"\n当前余额: ￥{money:.2f}")
        display_cart(shopping_cart)

        choice = input("\n请选择操作:\n1. 添加商品\n2. 退货\n3. 结算(Q/q也可结算)\n请输入选项: ")

        # 结算
        if choice.lower() in ['3', 'q']:
            break

        # 添加商品
        elif choice == '1':
            product_choice = input("请输入商品编号: ")

            try:
                choice_idx = int(product_choice) - 1
                if choice_idx < 0 or choice_idx >= len(products):
                    print("没有这个商品，别瞎弄！")
                    continue
            except ValueError:
                print("请输入有效的数字编号!")
                continue

            # 获取选择的商品
            product_name, product_price = products[choice_idx]

            # 检查是否有优惠
            if product_name == coupon_product:
                discounted_price = product_price * discount
                print(f"优惠券生效! {product_name} 从 ￥{product_price:.2f} 降至 ￥{discounted_price:.2f}")
            else:
                discounted_price = product_price

            # 检查余额是否足够
            if money >= discounted_price:
                # 添加到购物车 (存储商品名、实际支付价格和原价)
                shopping_cart.append((product_name, discounted_price, product_price))
                # 扣除金额
                money -= discounted_price
                print(f"恭喜，购买成功！您的卡余额还剩 ￥{money:.2f}")
            else:
                print(f"穷鬼，钱不够！请到其他超市购买!")

        # 退货
        elif choice == '2':
            if not shopping_cart:
                print("购物车是空的，无法退货")
                continue

            return_choice = input("请输入要退货的商品编号: ")

            try:
                return_idx = int(return_choice) - 1
                if return_idx < 0 or return_idx >= len(shopping_cart):
                    print("没有这个商品，别瞎弄！")
                    continue
            except ValueError:
                print("请输入有效的数字编号!")
                continue

            # 获取退货商品信息
            returned_product, returned_price, original_price = shopping_cart.pop(return_idx)
            # 退款
            money += returned_price
            print(f"已退货 {returned_product}, 退款 ￥{returned_price:.2f}, 当前余额: ￥{money:.2f}")

        else:
            print("无效的选项，请重新输入!")

    # 打印购物小票
    print("\n" + "=" * 30)
    print("         购物小票")
    print("=" * 30)
    print(f"购物时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"初始余额: ￥{original_money:.2f}")
    print(f"剩余余额: ￥{money:.2f}")
    print("-" * 30)

    if not shopping_cart:
        print("您没有购买任何商品")
    else:
        total = 0.0
        total_saved = 0.0  # 累计节省金额

        for idx, (name, price, original_price) in enumerate(shopping_cart, 1):
            print(f"{idx}. {name.ljust(8)} ￥{price:.2f}", end="")
            if price < original_price:
                saved = original_price - price
                total_saved += saved
                print(f" (节省 ￥{saved:.2f})")
            else:
                print()
            total += price

        print("-" * 30)
        print(f"购买数量: {len(shopping_cart)}件")
        print(f"商品总价: ￥{total:.2f}")
        if total_saved > 0:
            print(f"优惠节省: ￥{total_saved:.2f} (使用了{coupon_product}{int(discount * 10)}折优惠券)")
        print(f"实付金额: ￥{(original_money - money):.2f}")

    print("=" * 30)
    print("感谢您的光临!")
    print("=" * 30)


# 启动购物系统
shopping_system_v2()
